/*
	SQFuncs.c
	--------------------------------------------------
	Squirrel function registration. New functions and/or
	callback handlers are registered here.
*/

#include "SQFuncs.h"
#include "Callbacks.h"
#include "Defines.h"
#include "SQModule.h"
#include <stdio.h>

extern SQAPI sq;

_SQUIRRELDEF( onPlayerConnect )
{
	Player player = NULL;
	LU_RETURN retn = LU_OK;

	sq->getinstanceup( v, 2, &player, NULL );

	retn = PlayerConnect( player );

	sq->pushinteger( v, retn );
	return 1;
}

_SQUIRRELDEF( onPlayerJoin )
{
	Player player = NULL;
	LU_RETURN retn = LU_OK;
	
	sq->getinstanceup( v, 2, &player, NULL );

	retn = PlayerJoin( player );

	sq->pushinteger( v, retn );
	return 1;
}

_SQUIRRELDEF( onPlayerPart )
{
	Player player = NULL;
	SQInteger reason = 0;
	LU_RETURN retn = LU_OK;

	sq->getinstanceup( v, 2, &player, NULL );
	sq->getinteger( v, 3, &reason );

	retn = PlayerPart( player, reason );

	sq->pushinteger( v, retn );
	return 1;
}

_SQUIRRELDEF( onPlayerSpawn )
{
	Player player = NULL;
	SpawnClass spawn = NULL;
	LU_RETURN retn = LU_OK;

	sq->getinstanceup( v, 2, &player, NULL );
	sq->getinstanceup( v, 3, &spawn, NULL );
	
	retn = PlayerSpawn( player, spawn );

	sq->pushinteger( v, retn );
	return 1;
}

//--------------------------------------------------

SQInteger RegisterSquirrelFunc( HSQUIRRELVM v, SQFUNCTION f, const SQChar* fname, unsigned char ucParams, const SQChar* szParams )
{
	char szNewParams[ 32 ];

	sq->pushroottable( v );
	sq->pushstring( v, fname, -1 );
	sq->newclosure( v, f, 0 ); /* create a new function */

	if ( ucParams > 0 ) 
	{
		ucParams++; /* This is to compensate for the root table */

		sprintf( szNewParams, "t%s", szParams );
		sq->setparamscheck( v, ucParams, szNewParams ); /* Add a param type check */
	}

	sq->setnativeclosurename( v, -1, fname );
	sq->newslot( v, -3, SQFalse );
	sq->pop( v, 1 ); /* pops the root table */

	return 0;
}

void RegisterFuncs( HSQUIRRELVM v )
{
	// Register callback handlers here
	RegisterSquirrelFunc( v, onPlayerConnect, "onPlayerConnect", 0, 0 );
	RegisterSquirrelFunc( v, onPlayerJoin, "onPlayerJoin", 0, 0 );
	RegisterSquirrelFunc( v, onPlayerPart, "onPlayerPart", 0, 0 );
	RegisterSquirrelFunc( v, onPlayerSpawn, "onPlayerSpawn", 0, 0 );
}
